/*
 *  Author: Gary Kelly, gkelly2008@my.fit.edu
 *  Author: John Stevens, jstevens@fit.edu
 *  Class:  CSE 4232 - Network Programming
 *  Program: SQlite database synchronization user thread
 */
 
 
#include <iostream>
#include <limits.h>
#include <signal.h>
#include <sstream>


using namespace std;

//A function for displaying the results of the SQL commands
static int outputDB (void *asn, int argc, char* argv[], char* azColName[]) {
	//Output each column entry
	for (int i = 0; i < argc; i++) {
		string value = argv[i] ? argv[i] : "NULL";
		cout << azColName[i] << " = " << value << endl;
	}
	
	cout << endl;

	return 0;
}

void* userRun (void*) {
	while (1) {
		stringbuf input;

		//Get user input
		cout << "sqlite> ";
		cin.get (input, '\n');
		if (cin.good ()) {
			string command = input.str ();
			if (command.compare (".quit") == 0) {
				//Send signal to other threads and return to main thread
				//signal
				break;
			} else {
				char* cstr_err = "\0";
				
				//Lock the database and execute the SQL command
				sem_wait (&semDB);
				if (sqlite3_exec (db, command.c_str (), outputDB, 0, &cstr_err) != SQLITE_OK) {
					cerr << "SQL error: " << string (cstr_err) << endl;
					sqlite3_free (cstr_err);
				}
				sem_post (&semDB);
			}

			//Clear any input still in the stream
			cin.clear ();
			cin.ignore (numeric_limits<streamsize>::max (), '\n');
		//Bad input
		} else {
			cout << "Invalid input" << endl;
			cin.clear ();
			cin.ignore (numeric_limits<streamsize>::max (), '\n');
			pause ();
		}
	}
};
